import { useState, useEffect, useCallback, useRef } from 'react';
import { 
  MarketDataService, 
  createMarketDataService, 
  OrderBookData, 
  KlineData, 
  TickerStats,
  TickerData 
} from '../services/marketDataService';

export interface UseMarketDataOptions {
  symbol: string;
  interval?: string;
  dataSource?: 'binance' | 'coingecko' | 'mock';
  enableRealtime?: boolean;
}

export interface MarketDataState {
  orderBook: OrderBookData | null;
  klineData: KlineData[];
  tickerStats: TickerStats | null;
  currentPrice: number | null;
  loading: boolean;
  error: string | null;
}

export function useMarketData(options: UseMarketDataOptions) {
  const {
    symbol,
    interval = '1h',
    dataSource = 'mock',
    enableRealtime = false
  } = options;

  const [state, setState] = useState<MarketDataState>({
    orderBook: null,
    klineData: [],
    tickerStats: null,
    currentPrice: null,
    loading: true,
    error: null,
  });

  const serviceRef = useRef<MarketDataService | null>(null);
  const unsubscribeRefs = useRef<(() => void)[]>([]);

  // 初始化服务
  useEffect(() => {
    serviceRef.current = createMarketDataService(dataSource);
  }, [dataSource]);

  // 获取初始数据
  const fetchInitialData = useCallback(async () => {
    if (!serviceRef.current || !symbol) return;

    setState(prev => ({ ...prev, loading: true, error: null }));

    try {
      const [orderBook, klineData, tickerStats] = await Promise.all([
        serviceRef.current.getOrderBook(symbol),
        serviceRef.current.getKlineData(symbol, interval, 100),
        serviceRef.current.get24hrStats(symbol),
      ]);

      setState({
        orderBook,
        klineData,
        tickerStats,
        currentPrice: parseFloat(tickerStats.lastPrice),
        loading: false,
        error: null,
      });
    } catch (error) {
      setState(prev => ({
        ...prev,
        loading: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      }));
    }
  }, [symbol, interval]);

  // 设置实时数据订阅
  const setupRealtimeData = useCallback(() => {
    if (!serviceRef.current || !symbol || !enableRealtime) return;

    // 清理之前的订阅
    unsubscribeRefs.current.forEach(unsubscribe => unsubscribe());
    unsubscribeRefs.current = [];

    // 订阅价格更新
    const unsubscribeTicker = serviceRef.current.subscribeTicker(
      symbol,
      (tickerData: TickerData) => {
        setState(prev => ({
          ...prev,
          currentPrice: parseFloat(tickerData.price),
        }));
      }
    );

    // 订阅订单簿更新
    const unsubscribeOrderBook = serviceRef.current.subscribeOrderBook(
      symbol,
      (orderBookData: OrderBookData) => {
        setState(prev => ({
          ...prev,
          orderBook: orderBookData,
        }));
      }
    );

    unsubscribeRefs.current.push(unsubscribeTicker, unsubscribeOrderBook);
  }, [symbol, enableRealtime]);

  // 刷新数据的方法
  const refetch = useCallback(() => {
    fetchInitialData();
  }, [fetchInitialData]);

  // 主效果：获取初始数据和设置实时订阅
  useEffect(() => {
    fetchInitialData();
    setupRealtimeData();

    // 清理函数
    return () => {
      unsubscribeRefs.current.forEach(unsubscribe => unsubscribe());
      unsubscribeRefs.current = [];
    };
  }, [fetchInitialData, setupRealtimeData]);

  // 转换订单簿数据为组件可用格式
  const processedOrderBook = state.orderBook ? {
    buyOrders: state.orderBook.bids.map(([price, amount]) => ({
      price: parseFloat(price),
      amount: parseFloat(amount),
      total: parseFloat(price) * parseFloat(amount),
      side: 'buy' as const,
    })),
    sellOrders: state.orderBook.asks.map(([price, amount]) => ({
      price: parseFloat(price),
      amount: parseFloat(amount),
      total: parseFloat(price) * parseFloat(amount),
      side: 'sell' as const,
    })),
  } : null;

  // 转换K线数据为组件可用格式
  const processedKlineData = state.klineData.map(kline => ({
    time: kline.openTime,
    open: parseFloat(kline.open),
    high: parseFloat(kline.high),
    low: parseFloat(kline.low),
    close: parseFloat(kline.close),
    volume: parseFloat(kline.volume),
  }));

  return {
    ...state,
    orderBook: processedOrderBook,
    klineData: processedKlineData,
    refetch,
  };
}

// 专门用于获取多个交易对数据的Hook
export function useMultipleMarketData(symbols: string[], dataSource: 'binance' | 'coingecko' | 'mock' = 'mock') {
  const [data, setData] = useState<Record<string, TickerStats>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 使用JSON.stringify来稳定化symbols数组的依赖
  const symbolsKey = JSON.stringify(symbols);

  useEffect(() => {
    const symbolsArray = JSON.parse(symbolsKey);
    if (symbolsArray.length === 0) return;

    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        const service = createMarketDataService(dataSource);
        const results = await Promise.all(
          symbolsArray.map(async (symbol: string) => {
            try {
              const stats = await service.get24hrStats(symbol);
              return { symbol, stats };
            } catch (err) {
              console.error(`Error fetching data for ${symbol}:`, err);
              return null;
            }
          })
        );

        const newData: Record<string, TickerStats> = {};
        results.forEach((result) => {
          if (result) {
            newData[result.symbol] = result.stats;
          }
        });

        setData(newData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    // 设置定期刷新
    const interval = setInterval(fetchData, 10000); // 每10秒刷新一次

    return () => clearInterval(interval);
  }, [symbolsKey, dataSource]);

  return { data, loading, error };
}

// 专门用于实时价格的Hook
export function useRealtimePrice(symbol: string, dataSource: 'binance' | 'coingecko' | 'mock' = 'mock') {
  const [price, setPrice] = useState<number | null>(null);
  const [change24h, setChange24h] = useState<number | null>(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    if (!symbol) return;

    const service = createMarketDataService(dataSource);
    
    // 获取初始数据
    service.get24hrStats(symbol).then((stats) => {
      setPrice(parseFloat(stats.lastPrice));
      setChange24h(parseFloat(stats.priceChangePercent));
    }).catch(console.error);

    // 订阅实时价格
    const unsubscribe = service.subscribeTicker(symbol, (tickerData) => {
      setPrice(parseFloat(tickerData.price));
      setConnected(true);
    });

    return () => {
      unsubscribe();
      setConnected(false);
    };
  }, [symbol, dataSource]);

  return { price, change24h, connected };
}
